package com.shxy.cloudclassroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxy.cloudclassroom.entity.pojo.*;
import com.shxy.cloudclassroom.mapper.LearningResourceMapper;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.shxy.cloudclassroom.utils.SystemConstant.*;

@Service
public class LearningResourceServiceImpl extends ServiceImpl<LearningResourceMapper, LearningResource> implements LearningResourceService {
    
    @Resource
    private MajorService majorService;
    
    @Resource
    private OssService ossService;
    
    @Resource
    private DownloadHistoryService downloadHistoryService;
    
    @Resource
    private ViewHistoryService viewHistoryService;
    
    @Resource
    private UserService userService;

    @Override
    // 获取资源列表
    public List<LearningResource> getResourceList(Page<LearningResource> page, LambdaQueryWrapper<LearningResource> wrapper) {
        return this.list(page, wrapper);
    }

    @Override
    // 上传学习资源
    public Map<String, Object> uploadResource(LearningResource resource, MultipartFile file, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择文件");
                return result;
            }

            // 获取当前登录用户信息
            User loginUser = (User) session.getAttribute(LOGIN_USER);
            if (loginUser == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                return result;
            }
            
            // 上传文件到OSS
            String fileUrl = ossService.uploadAvatar(file);
            // 设置资源属性
            resource.setFileUrl(fileUrl);
            resource.setFileSize(file.getSize());
            resource.setUploaderId(loginUser.getId());
            resource.setDownloadCount(0);
            resource.setViewCount(0L);
            resource.setStatus(1); // 1表示正常状态
            resource.setCreatedTime(LocalDateTime.now());
            resource.setUpdatedTime(LocalDateTime.now());
            // 保存资源信息到数据库
            boolean saved = this.save(resource);
            result.put("success", saved);
            if (saved) {
                result.put("message", "资源上传成功");
                result.put("resourceId", resource.getId());
            } else {
                result.put("message", "资源上传失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传过程中发生错误: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 下载学习资源
    public void downloadResource(Integer id, HttpServletResponse response, HttpSession session) {
        User user = (User) session.getAttribute(LOGIN_USER);
        //TODO 实现登录下载
        if (user == null) {
            return;
        }
        //1.根据id查询资源
        LearningResource resource = null;
        try {
            resource = this.getById(id);
            //资源不存在或禁止下载状态
            if (resource == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "找不到资源!");
                return;
            }
            if (resource.getStatus() == 0) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "资源已被禁用!");
                return;
            }
            //2.增加下载次数
            resource.setDownloadCount(resource.getDownloadCount() + 1);
            this.update(resource,
                    new LambdaQueryWrapper<LearningResource>()
                            .eq(LearningResource::getId, resource.getId()));
            //3.更新下载历史
            DownloadHistory downloadHistory = new DownloadHistory();
            downloadHistory.setUserId(user.getId().longValue());
            downloadHistory.setResourceId(resource.getId().longValue());
            downloadHistory.setUploadTime(LocalDateTime.now());
            downloadHistoryService.save(downloadHistory);
            //4.重定向到文件URL，实际的下载由OSS负责
            response.sendRedirect(resource.getFileUrl());
        } catch (Exception e) {
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载失败");
            } catch (Exception ignored) {

            }
        }
    }

    @Override
    // 获取资源详情
    public com.shxy.cloudclassroom.entity.vo.ResourceDetailVO getResourceDetail(Integer id, HttpSession session) {
        //1.检验用户是否登录
        User user = (User) session.getAttribute(LOGIN_USER);
        if (user == null) {
            return null;
        }
        try {
            //2.根据id获取资源
            LearningResource resource = this.query().eq("id", id).one();
            if (resource == null) {
                return null;
            }
            //3.查询资源关联的专业
            Integer majorId = resource.getMajorId();
            Major major = majorService.getById(majorId);
            //4.增加资源浏览次数
            resource.setViewCount(resource.getViewCount() + 1);
            //5.增加浏览记录
            ViewHistory viewHistory = new ViewHistory();
            viewHistory.setUserId(user.getId().longValue());
            viewHistory.setResourceId(resource.getId().longValue());
            viewHistory.setViewTime(LocalDateTime.now());
            //6.更新数据库
            this.update(resource,
                    new LambdaQueryWrapper<LearningResource>().eq(LearningResource::getId, resource.getId()));
            viewHistoryService.save(viewHistory);
            //7.封装返回数据到VO
            com.shxy.cloudclassroom.entity.vo.ResourceDetailVO resourceDetailVO = new com.shxy.cloudclassroom.entity.vo.ResourceDetailVO();
            resourceDetailVO.setId(resource.getId());
            resourceDetailVO.setTitle(resource.getTitle());
            resourceDetailVO.setDescription(resource.getDescription());
            resourceDetailVO.setMajorName(major.getName());
            resourceDetailVO.setMajorId(major.getId());
            resourceDetailVO.setType(resource.getType());
            resourceDetailVO.setResourceType(resource.getResourceType());
            resourceDetailVO.setFileSize(resource.getFileSize());
            resourceDetailVO.setDownloadCount(resource.getDownloadCount());
            resourceDetailVO.setViewCount(resource.getViewCount());
            resourceDetailVO.setStatus(resource.getStatus());
            resourceDetailVO.setCreatedTime(resource.getCreatedTime());
            resourceDetailVO.setUpdatedTime(resource.getUpdatedTime());
            
            return resourceDetailVO;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    // 设置资源状态
    public Map<String, Object> setIsAvailable(Long id, Integer status) {
        boolean updated = this.update(new UpdateWrapper<LearningResource>().set("status", status).eq("id", id));
        Map<String, Object> result = new HashMap<>();
        result.put("success", updated);
        result.put("error", updated ? null : "删除失败!");
        return result;
    }
}